package com.base.cn.platform.os.statistics;

import com.base.cn.platform.os.common.logger.PageViewLogForm;
import com.base.cn.platform.os.common.utils.DateUtils;
import com.base.cn.platform.os.common.utils.ObjectUtils;
import com.base.cn.platform.os.service.manage.statistics.ZStatisticsPageViewCountService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ResourceUtils;

import java.io.File;
import java.util.*;
import java.util.stream.Collectors;

/**
 * PV统计工具类
 *
 * @author s.li
 * @date 2019/04/17
 */
@Slf4j
public class PVStatisticsUtils {

    /**
     * PV 数据统计
     * @param zStatisticsPageViewCountService PV统计服务接口
     */
    public static void pvStatistics(ZStatisticsPageViewCountService zStatisticsPageViewCountService){
        try {
            File classPathDir = ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX);
            File logsFileDir = new File(classPathDir,"/static/logs/pv");
            if(logsFileDir.exists()){
                String[] fileNameArr = logsFileDir.list();
                List<String> fileNameList = new ArrayList<>();
                if(ObjectUtils.isNotEmpty(fileNameArr)){
                    String exFileName = "pv-"+DateUtils.format(new Date(),"yyyy-MM-dd-HH")+".log";
                    List<String> logFileLineContextList = LogFileUtils.getLogFileLineContextList(logsFileDir,fileNameList,fileNameArr,exFileName);

                    //处理日志文件内容
                    List<Map<String,Object>> pvDataList = handlePVLogsContext(logFileLineContextList);
                    if(ObjectUtils.isNotEmpty(pvDataList)){
                        Map<String,Object> resultMap = zStatisticsPageViewCountService.createPageViewCount(pvDataList);
                        //删除文件
                        LogFileUtils.deleteLogFile(resultMap,logsFileDir,fileNameList);
                    }
                }
            }
        } catch (Exception e) {
            log.error("pvStatistics()--error",e);
        }
    }

    /**
     * (PV)处理日志文件内容
     * @param logFileLineContextList 内容列表，第个元素是日志文件中一行
     * @return List<Map<String,Object>>
     */
    private static List<Map<String,Object>> handlePVLogsContext(List<String> logFileLineContextList){
        if(ObjectUtils.isNotEmpty(logFileLineContextList)){
            List<Map<String,String>> mapList = getMapDataList(logFileLineContextList);
            if(ObjectUtils.isNotEmpty(mapList)){
                Map<String,List<Map<String,String>>> stringListMap = mapList.stream().collect(Collectors.groupingBy(e->e.get("tenantId")));
                List<Map<String,String>> dataList = stringListMap.get("0");
                List<Map<String,Object>> pvDataList = new ArrayList<>();
                if(ObjectUtils.isNotEmpty(dataList)){
                    Map<String,List<Map<String,String>>> listMap = dataList.stream().collect(Collectors.groupingBy(e->e.get("time")));
                    listMap.forEach((k,list)->{
                        Map<String,Object> map = new HashMap<>();
                        map.put("requestTime", DateUtils.parseDate(k,"yyyy-MM-dd HH"));
                        Map<String,List<Map<String,String>>> fromListMap = list.stream().collect(Collectors.groupingBy(e->e.get("form")));
                        Arrays.stream(PageViewLogForm.values()).forEach(form->{
                            List<Map<String,String>> formList = fromListMap.get(form.getKey());
                            if(ObjectUtils.isNotEmpty(formList)){
                                map.put(form.getColumnName(),formList.size());
                            }else{
                                map.put(form.getColumnName(),0);
                            }
                        });
                        pvDataList.add(map);
                    });
                    return pvDataList;
                }
            }
        }
        return null;
    }


    /**
     * 获取日志数据
     * @param logFileLineContextList
     * @return
     */
    private static List<Map<String,String>> getMapDataList(List<String> logFileLineContextList){
        List<Map<String,String>> mapList = new ArrayList<>();
        logFileLineContextList.forEach(lineContext->{
            String[] arr = lineContext.split("\\|");
            String ipAddr = arr[0];
            String form = arr[1];
            String time = arr[2];
            String tenantId = arr[3];
            Map<String,String> map = new HashMap<>();
            map.put("ipAddr",ipAddr);
            map.put("form",form);
            map.put("time",time.split(":")[0]);//只取到小时部分的时间
            map.put("tenantId",tenantId);
            mapList.add(map);
        });
        return mapList;
    }
}
